package whf.framework.workflow.service;

import java.io.InputStream;

import org.jbpm.graph.def.ProcessDefinition;

import whf.framework.exception.CreateException;
import whf.framework.exception.ServiceNotFoundException;
import whf.framework.exception.UpdateException;
import whf.framework.util.BeanFactory;
import whf.framework.workflow.dao.WorkflowDefinitionDAO;
import whf.framework.workflow.engine.WorkflowEngine;
import whf.framework.workflow.engine.WorkflowEngineImpl;
import whf.framework.workflow.entity.WorkflowDefinition;
import whf.framework.workflow.exception.WorkflowException;

/**
 * 服务对象具体实现，委托相应的dao对象实现相关操作
 * @author wanghaifeng
 * @email king@126.com
 * @modify 2008-06-21
 */
public class WorkflowDefinitionServiceImp extends whf.framework.service.ServiceImp<WorkflowDefinition> implements WorkflowDefinitionService {
	public void setWorkflowDefinitionDAO(WorkflowDefinitionDAO workflowDefinitionDAO) {
		this.entityDAO = workflowDefinitionDAO;
	}
	
	public static WorkflowDefinitionService getWorkflowDefinitionService() throws ServiceNotFoundException {
		return (WorkflowDefinitionService)BeanFactory.getService(WorkflowDefinitionServiceImp.class) ;
	}

	public WorkflowDefinition deploy(WorkflowDefinition definition) throws WorkflowException, UpdateException, CreateException{
		String path = definition.getPath();
		InputStream is = WorkflowDefinition.class.getClassLoader().getResourceAsStream(path);
		if(is == null) throw new WorkflowException("process definition file:'" + path + "' can not be found!");
		try{
			WorkflowDefinition master = definition;
			if(definition.getParent() != null) {
				master = definition.getParent();
			}
			master.setVersion(master.getVersion() + 1);
			// 发布流程
			WorkflowEngine workflowEngine = new WorkflowEngineImpl();
			ProcessDefinition pd = workflowEngine.deployDefinition(is);
			// 创建版本发布信息
			WorkflowDefinition newDefinition = new WorkflowDefinition();
			newDefinition.setParent(definition);
			newDefinition.setName(definition.getName());
			newDefinition.setRemarks(definition.getRemarks());
			newDefinition.setVersion(master.getVersion());
			newDefinition.setPath(definition.getPath());
			newDefinition.setProcessDefinition(pd.getId());
			this.entityDAO.create(newDefinition);
			// 修改最新的流程定义到主信息
			master.setCurrentVersion(newDefinition);
			master.setProcessDefinition(pd.getId());
			this.entityDAO.update(master);
			//
			return newDefinition;
		} finally {
			try{
				is.close();
			}catch(Exception e){
				throw new WorkflowException(e);
			}
		}
	}

	public void changeCurrent(WorkflowDefinition definition) throws UpdateException {
		WorkflowDefinition master = definition;
		if(definition.getParent() != null) {
			master = definition.getParent();
			master.setCurrentVersion(definition);
			this.entityDAO.update(master);
		}
	}
	
} 